package com.it.admin.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.admin.AdminCategoryService;
import com.it.dao.CategoryMapper;
import com.it.pojo.Category;
import com.it.pojo.params.BasePage;
import com.it.pojo.vo.category.AdminCategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class AdminCategoryServiceImpl implements AdminCategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public List<AdminCategoryVO> listCategories() {
        List<Category> categories = categoryMapper.selectList(null);
        List<AdminCategoryVO> adminCategoryVOS = copyList(categories);
        return adminCategoryVOS;
    }

    @Override
    public int insertCategory(String categoryName) {
        Category category = new Category();
        Date date = new Date();
        category.setGmtCreate(date);
        category.setGmtModified(date);
        category.setCategoryName(categoryName);

        return categoryMapper.insert(category);
    }

    @Override
    public Map<String, Object> listCategories(BasePage basePage) {
        Page<Category> page = new Page<>(basePage.getPageNum(), basePage.getLimit());
        Page<Category> categoryPage = categoryMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        map.put("total", categoryPage.getTotal());
        map.put("listCategory", categoryPage.getRecords());
        return map;
    }

    @Override
    public int deleteCategoryById(Integer categoryId) {

        return categoryMapper.deleteById(categoryId);
    }

    @Override
    public int updateCategoryById(Category category) {
        System.out.println("category = " + category);
        category.setGmtModified(new Date());
        return categoryMapper.updateById(category);
    }

    @Override
    public String getCategory(Integer categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category != null) {
            return category.getCategoryName();
        }
        return "";
    }

    private AdminCategoryVO copy(Category category) {
        AdminCategoryVO adminCategoryVO = new AdminCategoryVO();
        BeanUtils.copyProperties(category, adminCategoryVO);
        return adminCategoryVO;
    }

    private List<AdminCategoryVO> copyList(List<Category> categoryList) {
        List<AdminCategoryVO> list = new ArrayList<>();
        for (Category category : categoryList) {
            list.add(copy(category));
        }
        return list;
    }
}
